//
//  DLImageVerifyAlertView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2019/1/10.
//  Copyright © 2019 delongzhitou. All rights reserved.
//

#import "DLImageVerifyAlertView.h"

@interface DLImageVerifyAlertView()

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UIImageView *imageV;

@property (nonatomic, strong) UIButton *nextButton;

@end

@implementation DLImageVerifyAlertView


+ (instancetype)showSmsVerifyAlert {
    static DLImageVerifyAlertView* smsVerifyAlert = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        smsVerifyAlert = [[DLImageVerifyAlertView alloc] initWithFrame:CGRectMake(0, 0,kAutoWidth(280), kAutoWidth(192))];
        smsVerifyAlert.layer.cornerRadius = 10;
        smsVerifyAlert.clipsToBounds = YES;
    });
    return smsVerifyAlert;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        [self layoutSubControls];
    }
    return self;
}
- (void) getImageVerifyCode {
    
    NSString *postUrl = HTTPGetImageVerifyCode;
    NSDictionary *postDic = @{
                              @"mobile" : self.phoneNum,
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            
            NSString *base64String = [NSString stringWithFormat:@"%@", responseObject[@"result"][@"data"]];
            if ([base64String containsString:@"data:image/jpg;base64"]) {
                
                NSArray *arr = [base64String componentsSeparatedByString:@","];
                // 将base64字符串转为NSData
                NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:[arr lastObject] options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
                // 将NSData转为UIImage
                UIImage *decodeImage = [UIImage imageWithData:decodeData];
                NSLog(@"%@", decodeImage);
                self.imageV.image = decodeImage;
            }
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}
- (void) layoutSubControls {
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.frame = CGRectMake(33, 0, self.width - 66, 60);
    titleLabel.font = kSystemFont(15);
    titleLabel.text = @"请输入图形验证码";
    titleLabel.textColor = kDLNormalBlackColor;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:titleLabel];
//    titleLabel.backgroundColor = [UIColor redColor];
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.frame = CGRectMake(titleLabel.left, titleLabel.bottom, titleLabel.width - 40, 55);
    bgView.layer.borderWidth = 0.5;
    bgView.layer.borderColor = kColorRGB(200, 200, 200).CGColor;
    [self addSubview:bgView];
    
    UIButton *closeButton = [UIButton buttonWithType:0];
    closeButton.frame = CGRectMake(self.width - 40, 20, 14, 14);
    [closeButton setImage:[UIImage imageNamed:@"guanbi"] forState:UIControlStateNormal];
    [self addSubview:closeButton];
    [closeButton addTarget:self action:@selector(closeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    UITextField *smscodeTF = [UITextField new];
    self.smscodeTF = smscodeTF;
    smscodeTF.frame = CGRectMake(10, 0, bgView.width / 2 - 10, bgView.height);
    smscodeTF.borderStyle = UITextBorderStyleNone;
    smscodeTF.keyboardType = UIKeyboardTypeNumberPad;
    smscodeTF.font = kSystemFont(14);
    smscodeTF.placeholder = @"请输入";
    [smscodeTF addTarget:self action:@selector(smscodeTFTextChange:) forControlEvents:UIControlEventEditingChanged];
    [bgView addSubview:smscodeTF];
    
    UIImageView *imageV = [UIImageView new];
    self.imageV = imageV;
    imageV.backgroundColor = [UIColor whiteColor];
    imageV.frame = CGRectMake(smscodeTF.right, smscodeTF.top, bgView.width - smscodeTF.width, smscodeTF.height);
    [bgView addSubview:imageV];
    
    UIButton *changeImageVerifyButton = [UIButton buttonWithType:0];
    [changeImageVerifyButton setImage:[UIImage imageNamed:@"shuaxin"] forState:UIControlStateNormal];
    changeImageVerifyButton.frame = CGRectMake(bgView.right + 20, bgView.top + 5, titleLabel.width - bgView.width, imageV.height - 10);
    [changeImageVerifyButton addTarget:self action:@selector(changeImageVerifyButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:changeImageVerifyButton];
//    changeImageVerifyButton.backgroundColor = [UIColor greenColor];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton = nextButton;
    nextButton.frame = CGRectMake(25, self.height - 60, self.width - 50, 40);
    [nextButton setBackgroundImage:[UIImage imageNamed:@"loginbtnbg"] forState:UIControlStateNormal];
    [nextButton setTitle:@"确认" forState:UIControlStateNormal];
    nextButton.titleLabel.font = kSystemFont(15);
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextButton.backgroundColor = kDLBtnNormalBgColor;
    [self addSubview:nextButton];
    nextButton.layer.cornerRadius = 20;
    nextButton.clipsToBounds = YES;
    
    [nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
}
- (void) closeButtonClick {
    [self alertDismiss];
}
- (void) changeImageVerifyButtonClick {
    [self getImageVerifyCode];
}
- (void) smscodeTFTextChange:(UITextField *)textField {
    
    if (textField.text.length >4) {
        NSString *str = textField.text;
        textField.text = [str substringToIndex:4];
    }
}
- (void) nextButtonClick {
    
    if (self.smscodeTF.text.length < 4) {
        
        [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的验证码" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    NSString *postUrl = HTTPCheckImageVerifyCode;
    NSDictionary *postDic = @{
                              @"mobile" : self.phoneNum,
                              @"imageCode" : self.smscodeTF.text
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
//            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
            [self endEditing:YES];
            [self alertDismiss];
            
            if (self.nextButtonClickBlock) {
                self.nextButtonClickBlock();
            }
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}

- (void) alertShow {
    [super alertShow];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
